package com.xuecheng.framework.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName FeignClientInterceptor
 * @Description (feign拦截器，拦截feign的请求，给请求添加头)
 * @date 2020/3/13 14:38
 * @since V1.0
 */

public class FeignClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null){
            HttpServletRequest request = requestAttributes.getRequest();
            //获取所有的头名称
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null){
                while (headerNames.hasMoreElements()){
                    String heandName = headerNames.nextElement();
                    String headValue = request.getHeader(heandName);
                    //找到jwt令牌，添加到feign中
                    if (heandName.equals("authorization")){
                        template.header(heandName,headValue);
                        break;
                    }
                }
            }
        }
    }
}
